/*
 *  (C) Copyright 2007 Insula Tecnologia da Informacao Ltda.
 * 
 *  This file is part of Jazz.
 *
 *  Jazz is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Jazz is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with Jazz.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.openinsula.jazz.binding;

import java.lang.reflect.Field;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openinsula.jazz.stereotype.Binding;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.ReflectionUtils.FieldCallback;

/**
 * {@link org.springframework.beans.factory.config.BeanPostProcessor}
 * implementation that searchs for field with binding to model properties. Such
 * members to be binded are detected through the {@link Binding} annotation.
 * 
 * @author Edson Yanaga
 * @since 1.0
 * @see Binding
 * @see BindingAttribute
 */
public class BindingAnnotationBeanPostProcessor implements BindingProvider, BeanPostProcessor, BeanFactoryAware {

	protected final Log logger = LogFactory.getLog(getClass());

	private ListableBeanFactory beanFactory;

	private List<BindingAttribute> bindingAttributeList = new LinkedList<BindingAttribute>();

	public List<BindingAttribute> getBindingAttributes() {
		return bindingAttributeList;
	}

	@Override
	public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
		ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() {
			@Override
			public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
				field.setAccessible(true);
				Binding binding = field.getAnnotation(Binding.class);
				if (binding != null) {
					Object model = findMatchingBean(binding);
					BindingAttribute bindingAttribute = new DefaultBindingAttribute(bean, field, model, binding
							.property());

					if (logger.isDebugEnabled()) {
						logger.debug("Found Binding " + bindingAttribute.toString());
					}

					bindingAttributeList.add(bindingAttribute);
				}
			}
		});

		return bean;
	}

	@SuppressWarnings("unchecked")
	protected Object findMatchingBean(Binding binding) {
		Class<?> beanType = binding.beanType();
		String beanName = binding.beanName();

		if (!"".equals(beanName)) {
			Object bean = beanFactory.getBean(beanName);
			if (bean != null) {
				return bean;
			}
			else {
				throw new NoSuchBeanDefinitionException(beanName);
			}
		}
		else if (!(beanType == Void.class)) {
			return BeanFactoryUtils.beanOfType(beanFactory, beanType);
		}
		else {
			throw new IllegalArgumentException("You must provide beanName OR beanType for @Binding annotation.");
		}
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}

	@Override
	public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
		if (!(beanFactory instanceof ConfigurableListableBeanFactory)) {
			throw new IllegalArgumentException(
					"BindingAnnotationBeanPostProcessor requires a ConfigurableListableBeanFactory");
		}
		this.beanFactory = (ListableBeanFactory) beanFactory;
	}

}